package com.xm.hiber.dao;

import com.xm.hiber.entity.ClassRoom;
import com.xm.hiber.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ClassRoomDao {
    public void saveClassRoom(ClassRoom classRoom) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.save(classRoom);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void updateClassRoom(ClassRoom classRoom) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.update(classRoom);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void deleteClassRoom(int id) {

        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // Delete a classRoom object
            ClassRoom classRoom = session.get(ClassRoom.class, id);
            if (classRoom != null) {
                session.delete(classRoom);
                System.out.println("classRoom is deleted");
            }

            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public ClassRoom getClassRoom(int id) {

        Transaction transaction = null;
        ClassRoom classRoom = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // get an classRoom object
            classRoom = session.get(ClassRoom.class, id);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
        return classRoom;
    }
}
